﻿using System.Xml;

namespace DotnetUtil.Xml
{
    public static class XmlHelper
    {
        public static bool GetNodeInnerInt(XmlNode node, string xpath, out int value)
        {
            var text = node?.SelectSingleNode(xpath)?.InnerText.Trim();
            return int.TryParse(text, out value);
        }

        public static bool GetNodeInnerStr(XmlNode node, string xpath, out string value)
        {
            value = node?.SelectSingleNode(xpath)?.InnerText.Trim();
            return !string.IsNullOrEmpty(value);
        }

        public static void SetNodeInnerValue(XmlNode node, string xpath, string text)
        {
            var item = node?.SelectSingleNode(xpath);
            if (item != null)
            {
                item.InnerText = text;
            }
        }

        public static bool GetNodeAttributeInt(XmlNode node, string xpath, out int value)
        {
            var text = node?.Attributes?.GetNamedItem(xpath)?.Value?.Trim();
            return int.TryParse(text, out value);
        }

        public static bool GetNodeAttributeStr(XmlNode node, string xpath, out string value)
        {
            value = node?.Attributes?.GetNamedItem(xpath)?.Value?.Trim();
            return !string.IsNullOrEmpty(value);
        }

        public static void SetNodeAttributeValue(XmlNode node, string xpath, string text)
        {
            var item = node?.Attributes?.GetNamedItem(xpath);
            if (item != null)
            {
                item.Value = text;
            }
        }
    }
}
